package com.jlboot.core.util;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jlboot.model.po.sys.SysDeleteLog;

import java.util.Date;

/**
 * @author wangsanfei
 * @version 1.0
 * Create by 2024/1/29 22:46
 */
public class CrudUtil {

    /**
     * 更新部分字段，新增和编辑，不建议使用
     * @param table
     * @param id
     * @param fields
     * @param values
     */
    public static Record updateField(String table,String id,String[] fields,Object[] values){
        if(fields.length!=values.length){
            throw new RuntimeException("参数错误");
        }
        Record r=Db.findById(table,id);
        for (int i = 0; i < fields.length; i++) {
            r.set(fields[i],values[i]);
            r.set("create_time",new Date());
            r.set("update_time",new Date());
            r.set("create_by", LoginUtil.getUserId());
            r.set("update_by",LoginUtil.getUserId());
            Db.save(table,r);
        }
        return r;
    }

    /**
     * 批量删除
     */
    public static Integer[] DelMoreModel(String table, String... ids) {
        if(ids.length>100){
            throw new RuntimeException("单次不能超过100");
        }
        int succ = 0, error = 0;
        for (String id : ids) {
            Record m= Db.findById(table,id);
            if(m!=null){
                SysDeleteLog.dao.addDeleteLog(table,id);
                Db.deleteById(table,id);
                succ++;
            }else{
                error++;
            }

        }
        Integer[] result={succ,error};
        return result;
    }

    /**
     * 批量删除
     */
    public static Integer[] DelMoreModelTag(String table, String... ids) {

        if(ids.length>100){
            throw new RuntimeException("单次不能超过100");
        }

        ///////////////////////////////////
        int succ = 0, error = 0;
        for (String id : ids) {

            Record m= Db.findById(table,id);
            if(m!=null){
                SysDeleteLog.dao.addDeleteLog(table,id);
                m.set("del_tag",1);
                Db.update(table,m);
                succ++;
            }else{
                error++;
            }
        }
        Integer[] result={succ,error};
        return result;
    }

}
